#include <iostream>
#include <cstring>
using namespace std;

typedef pair<int, int> PII;

const int N = 110;
const int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
PII q[N * N];
int l = 0, r = -1; //创建一个新的队列来存储接下来的行动
int g[N][N], d[N][N];
int n, m;

int bfs(PII x)
{
    q[++r] = x;  //将起点入队
    d[0][0] = 0; //标记起点已经走过了，而且行动步数为0
    while (r >= l)
    {
        PII t = q[l++];
        for (int i = 0; i < 4; ++i)
        {
            int x = t.first + dx[i], y = t.second + dy[i];
            if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1)
            {
                d[x][y] = d[t.first][t.second] + 1;
                q[++r] = PII(x, y);
            }
        }
    }
    return d[n - 1][m - 1];
}

int main()
{
    cin >> n >> m;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < m; ++j)
            cin >> g[i][j];  //初始输入的迷宫矩阵
    memset(d, -1, sizeof d); //初始化记录步数的矩阵
    cout << bfs({0, 0});
    return 0;
}